package com.example.hellonotes.activity;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import com.example.hellonotes.BaseActivity;
import com.example.hellonotes.NotesDB;
import com.example.hellonotes.R;
import com.example.hellonotes.R.id;
import com.example.hellonotes.R.layout;
import com.example.hellonotes.adapter.WriteStatusGridImgsAdapter;
import com.example.hellonotes.bmob.bmobDb;
import com.example.hellonotes.entity.Person2;
import com.example.hellonotes.utils.GetThumbnail;
import com.example.hellonotes.utils.ImageUtils;
import com.example.hellonotes.utils.TitleBuilder;
import com.example.hellonotes.utils.ToastUtils;
import com.example.hellonotes.widget.WrapHeightGridView;
import com.nostra13.universalimageloader.core.ImageLoader;

import android.R.string;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Path;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.VideoView;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.listener.SaveListener;


/**
 * 添加内容的界面
 * @author Administrator
 *
 */
public class AddActivity extends BaseActivity  implements OnClickListener,OnItemClickListener{

	private ImageView iv_image,iv_at,iv_topic,iv_emoji,iv_add;
	private EditText editText;
	private NotesDB notesDB;
	private SQLiteDatabase dbWrite;
	private Uri imgUris;
	private ArrayList<Uri> imgUriss = new ArrayList<Uri>();
	private ArrayList<String> imUrls = new ArrayList<String>();
	//private ArrayList imgUrisss;
	private com.example.hellonotes.adapter.WriteStatusGridImgsAdapter statusImgsAdapter;
	// 添加的九宫格图片
	private WrapHeightGridView gv_write_status;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO 自动生成的方法存根
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_add);
		initTitle();
		initView();
	}
	
	/**
	 * 初始化View
	 */
	public void initView() {
		
		// 添加的九宫格图片
		gv_write_status = (WrapHeightGridView) findViewById(R.id.gv_write_status);
		editText = (EditText)findViewById(R.id.edit);
		iv_image = (ImageView)findViewById(R.id.iv_image);
		iv_at = (ImageView)findViewById(R.id.iv_at);
		iv_topic = (ImageView)findViewById(R.id.iv_topic);
		iv_emoji = (ImageView)findViewById(R.id.iv_emoji);
		iv_add = (ImageView)findViewById(R.id.iv_add);
		statusImgsAdapter = new WriteStatusGridImgsAdapter(this, imgUriss, gv_write_status);
		gv_write_status.setAdapter(statusImgsAdapter);
		gv_write_status.setOnItemClickListener(this);
		iv_image.setOnClickListener(this);
		iv_at.setOnClickListener(this);
		iv_topic.setOnClickListener(this);
		iv_emoji.setOnClickListener(this);
		iv_add.setOnClickListener(this);
		notesDB = new NotesDB(this);
		dbWrite = notesDB.getWritableDatabase();
		
		
		
		
	}
	
	/**
	 * 初始化标题栏
	 */
	private void initTitle(){
		new TitleBuilder(this).setLeftImage(R.drawable.navigationbar_back_highlighted)
		.setRightImage(R.drawable.compose_emotion_delete_highlighted)
		.setRightOnClickListener(this)
		.setTitleText(getTime())
		.setLeftOnClickListener(this);
	}
			
	
	
	/**
	 * 更新图片显示
	 */
	private void updateImgs() {
		if(imgUriss.size() > 0) {
			gv_write_status.setVisibility(View.VISIBLE);
			statusImgsAdapter.notifyDataSetChanged();
		} else {
			gv_write_status.setVisibility(View.GONE);
		}
	}
	
	
	public String getTime() {
		SimpleDateFormat DateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
		Date curDate = new Date();
		String str = DateFormat.format(curDate);
		return str;
	}
	
	public String getImgTime() {
		SimpleDateFormat DateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
		Date curDate = new Date();
		String str = DateFormat.format(curDate);
		return str;
	}
	
	
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO 自动生成的方法存根
		super.onActivityResult(requestCode, resultCode, data);
		
		
		switch (requestCode) {
		//来自图库的照片
		case ImageUtils.REQUEST_CODE_FROM_ALBUM:
			if(resultCode == RESULT_CANCELED) {
				return;
			}
			Uri imageUri = data.getData();
			imgUris = imageUri;
			imgUriss.add(imgUris);
			
			
			
			/**
			 * 获取图片uri 的绝对路径
			 */
			 String[] proj = {MediaStore.Images.Media.DATA}; 
	         //好像是android多媒体数据库的封装接口，具体的看Android文档
	         Cursor cursor = managedQuery(imgUris, proj, null, null, null); 
	         //按我个人理解 这个是获得用户选择的图片的索引值
	         int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
	         //将光标移至开头 ，这个很重要，不小心很容易引起越界
	         cursor.moveToFirst();
	         //最后根据索引值获取图片路径
	         String path = cursor.getString(column_index);
			
			imUrls.add(path);
			
			
			
			updateImgs();
			break;
		//来自相机的照片
		case ImageUtils.REQUEST_CODE_FROM_CAMERA:
			//RESULT_CANCELED 代表取消操作了
			if (resultCode == RESULT_CANCELED) {
				ImageUtils.deleteImageUri(this,ImageUtils.imageUriFromCamera );
			}else {
				Uri imageUriCamera = ImageUtils.imageUriFromCamera;
				imgUris = imageUriCamera;
				imgUriss.add(imgUris);
				updateImgs();
			}
		
			}
		}
		
	/**
	 * 往数据库里添加数据的方法
	 */
	public void addDB() {
		ContentValues cv = new ContentValues();  //用来存储基本数据的类
		cv.put(NotesDB.CONTENT, editText.getText().toString());
		cv.put(NotesDB.TIME, getTime());
		cv.put(NotesDB.PATH, imgUriss+"");
		dbWrite.insert(NotesDB.TABLE_NAME, null, cv);	
}

	/**
	 * 添加数据至Bmob后端
	 *//*
	public void addBmob() {
		bmobDb db = new bmobDb();
		BmobUser bmobUser = BmobUser.getCurrentUser(this);
		db.add(this,bmobUser,editText.getText().toString(),imgUris+"");
	}*/
	
	
	
	
	public void uploadFile() {
		bmobDb db = new bmobDb();
		
		/**
		 * 获取图片uri 的绝对路径
		 */
		 String[] proj = {MediaStore.Images.Media.DATA}; 
         //好像是android多媒体数据库的封装接口，具体的看Android文档
         Cursor cursor = managedQuery(imgUris, proj, null, null, null); 
         //按我个人理解 这个是获得用户选择的图片的索引值
         int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
         //将光标移至开头 ，这个很重要，不小心很容易引起越界
         cursor.moveToFirst();
         //最后根据索引值获取图片路径
         String path = cursor.getString(column_index);

         
         
		 db.uploadFile(this,path,editText.getText().toString());
	}
	
	/*public void uploadFileString() {
		bmobDb db = new bmobDb();
		*//**
		 * 获取图片uri 的绝对路径
		 *//*
		 String[] proj = {MediaStore.Images.Media.DATA}; 
         //好像是android多媒体数据库的封装接口，具体的看Android文档
         Cursor cursor = managedQuery(imgUris, proj, null, null, null); 
         //按我个人理解 这个是获得用户选择的图片的索引值
         int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
         //将光标移至开头 ，这个很重要，不小心很容易引起越界
         cursor.moveToFirst();
         //最后根据索引值获取图片路径
         String path = cursor.getString(column_index);
         db.uploadFileString(this,path,editText.getText().toString());
         
	}*/
	
	/**
	 * 上传多图
	 */
	public void uploadFiles() {
		bmobDb db = new bmobDb();
		
				
		//1.去除前后大括号
		String u =imUrls.toString();
		System.out.println("u :"+u);
		String uris = u.substring(1,(u).length()-1);
		System.out.println("uris :"+uris);
		//去除空格
		String uriss = uris.replace(" ", "");
		System.out.println("uriss:"+uriss);
		//将string转换为数组以逗号为分隔符
		String[] uri = uriss.split(",");
		//将String数组转换为集合
		for (int i = 0; i < uri.length; i++) {
			System.out.println("uri :"+uri[i]);
		}
		
		db.uploadFiles(this, uri, editText.getText().toString());
	}
	
	
	
	
	
	@Override
	public void onClick(View v) {
		// TODO 自动生成的方法存根
		switch (v.getId()) {	
		case R.id.iv_image:
			ImageUtils.showImagePickDialog(this);
			break;
		case R.id.iv_at:
			System.out.println("at");
			break;
		case R.id.iv_topic:
			System.out.println("topic");
			break;
		case R.id.iv_emoji:
			System.out.println("emoji");
			break;
		case R.id.iv_add:
			System.out.println("add");
			break;
		case R.id.titlebar_iv_left:
			if (editText.getText().toString().equals("") && imgUris == null ) {
				finish();
			} else {
				addDB();
				uploadFile();
				//uploadFiles();
				//uploadFileString();
				//addBmob();
				finish();
			}
			break;
		case R.id.titlebar_iv_right:
			System.out.println("delete");
			break;
		}
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		
		//获取所点击ITEM的所应用的适配器
				Object itemAdapter = parent.getAdapter();
				//判断适配器的值 （九宫格图片）
				if(itemAdapter instanceof WriteStatusGridImgsAdapter) {
					if(position == statusImgsAdapter.getCount() - 1) {
						ImageUtils.showImagePickDialog(this);
					}
		
	}

	
}
}
